﻿using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using THANHTUNGO.Portal.Components.Security;
using THANHTUNGO.Portal.Components.UI;
using THANHTUNGO.Portal.Modules.DOWNLOAD.Components;

namespace THANHTUNGO.Portal.Modules.DOWNLOAD.Pages
{
    public partial class ItemEdit : AddEditItemPage
    {
        private void buildCategory()
        {
            DataSet ds = Category.SelectAll(this.ModuleID);
            DataRow[] rootRows = ds.Tables[0].Select("ParentID = 0");

            foreach (DataRow row in rootRows)
            {
                cbCategory.Items.Add(new ListItem(row["Name"].ToString(), row["ID"].ToString()));
                DataRow[] childRows = ds.Tables[0].Select("ParentID = " + row["ID"]);
                if (childRows.Length > 0)
                {
                    foreach (DataRow childRow in childRows)
                    {
                        cbCategory.Items.Add(new ListItem("» " + childRow["Name"], childRow["ID"].ToString()));
                    }
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.buildCategory();

                lblCreationTime.Text = DateTime.Today.ToShortDateString();
                lblCreatedBy.Text = PortalSecurity.CurrentUser.Identity.Email;

                if (this.ItemID > 0)
                {
                    Item item = Item.Load(this.ItemID);
                    if (item != null)
                    {
                        cbCategory.SelectedValue = item.CategoryID.ToString();
                        txtTitle.Text = item.Title;
                        txtSubTitle.Text = item.SubTitle;
                        txtDescription.Text = Server.HtmlDecode(item.Description);
                        txtImageUrl.Text = item.ImageUrl;

                        string[] urls = item.Url.Split('|');
                        txtUrl.Text = urls[0];
                        if (urls.Length > 1) txtUrl01.Text = urls[1];
                        if (urls.Length > 2) txtUrl02.Text = urls[2];
                        if (urls.Length > 3) txtUrl02.Text = urls[2];

                        txtFileSize.Text = item.FileSize.ToString();
                        cbFileSize.SelectedIndex = 0;

                        txtFileType.Text = item.FileType;
                        txtTotalDownloads.Text = item.TotalDownloads.ToString("N0");
                        txtKeywords.Text = item.Keywords;
                        lblCreatedBy.Text = item.CreatedBy;
                        lblCreationTime.Text = item.CreationTime.ToString();
                    }
                }
                else
                {
                    btnDelete.Visible = false;
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    int categoryID = cbCategory.SelectedValue == string.Empty ? 0 : Convert.ToInt32(cbCategory.SelectedValue);
                    Item item = new Item();
                    item.CategoryID = categoryID;
                    item.Title = txtTitle.Text;
                    item.SubTitle = txtSubTitle.Text;
                    item.Description = Server.HtmlEncode(txtDescription.Text);
                    item.ImageUrl = txtImageUrl.Text;
                    item.Url = txtUrl.Text;

                    if (txtUrl01.Text.Length > 0) item.Url += "|" + txtUrl01.Text;
                    if (txtUrl02.Text.Length > 0) item.Url += "|" + txtUrl02.Text;
                    if (txtUrl03.Text.Length > 0) item.Url += "|" + txtUrl03.Text;

                    double filesize = Convert.ToDouble(txtFileSize.Text);
                    if (cbFileSize.SelectedValue == "KB") filesize = filesize*1024;
                    else if (cbFileSize.SelectedValue == "MB") filesize = filesize*1024*1024;
                    else if (cbFileSize.SelectedValue == "GB") filesize = filesize*1024*1024*1024;
                    item.FileSize = Convert.ToDecimal(filesize);

                    item.FileType = txtFileType.Text;
                    item.Keywords = txtKeywords.Text;

                    item.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;

                    if (this.ItemID == 0)
                    {
                        item.CreationTime = DateTime.Now;
                        item.Insert();
                    }
                    else
                    {
                        item.CreationTime = DateTime.Parse(lblCreationTime.Text);
                        item.ID = Convert.ToInt32(Request.QueryString["itemID"]);
                        item.Update();
                    }

                    this.ReturnToReferrerPage();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["itemID"] != null)
            {
                Item.Delete(Convert.ToInt32(Request.QueryString["itemID"]));
                this.ReturnToReferrerPage();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.ReturnToReferrerPage();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fuFileUpload.PostedFile != null)
            {
                string[] s = fuFileUpload.PostedFile.FileName.Split('\\');
                string filename = s[s.Length - 1];
                fuFileUpload.PostedFile.SaveAs(Server.MapPath(string.Format("~/Data/{0}", Request.QueryString["module"])) + "/" + filename);
                HttpContext.Current.Response.Write("<script>alert('Upload thành công');</script>");
            }
        }
    }
}